package com.mchat.communication.process.message.impl;

import com.mchat.common.dto.bo.OnlineUser;
import com.mchat.communication.process.message.MessageProcessor;
import com.mchat.communication.process.message.MessageType;
import com.mchat.communication.protocol.IMMessage;
import com.mchat.communication.service.OnlineUserService;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.mchat.communication.service.impl.OnlineUserServiceImpl.USER_SEQ;

@Component
public class LogoutMsgProcessor implements MessageProcessor {
    @Resource
    private OnlineUserService onlineUserService;

    @Override
    public void process(Channel client, IMMessage message) {
        OnlineUser user = null;
        if (client != null) {
            String userSeq = client.attr(USER_SEQ).get();
            user = onlineUserService.getUserBySeq(userSeq);
        }
        if (user != null) {
            sendLogoutMessage(user);
            onlineUserService.removeUser(user);
        }

    }

    private void sendLogoutMessage(OnlineUser user) {
        IMMessage msg = new IMMessage();
        msg.setSender(user.getUserName());
        msg.setAction(MessageType.LOGOUT.getType());
        msg.setOnline(onlineUserService.countOnlineUsers());
        msg.setContent(user.getUserName() + " 退出聊天！");
        msg.setReceiver("ALL");
        onlineUserService.sendMessage(user, msg);
    }
}
